package com.hk.service.order.impl;

import com.hk.commons.StringHelper;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Created by lipei on 2017/9/25.
 */
@Service
public class FundsOrderImpl implements Callable<Map<String, Object>> {

    private Logger logger = LoggerFactory
            .getLogger(FundsOrderImpl.class);

    @Autowired
    private YingmiApiUtils utils;

    public String phonenum;

    public String accountId;

    public String userId;

    public FundsOrderImpl(String phonenum, String accountId, String userId) {

        this.accountId = accountId;

        this.phonenum = phonenum;

        this.userId = userId;
    }

    public FundsOrderImpl() {
    }

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    public String getPhonenum() {
        return phonenum;
    }

    public void setPhonenum(String phonenum) {
        this.phonenum = phonenum;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public YingmiApiUtils getUtils() {
        return utils;
    }

    public void setUtils(YingmiApiUtils utils) {
        this.utils = utils;
    }

    @Override
    public Map<String, Object>  call() throws Exception {
        Map<String, Object> fundsObject=new HashMap<>();
        fundsObject.put("fundsAllCount", 0);
        fundsObject.put("allFundsMoney", BigDecimal.valueOf(0));
        fundsObject.put("fundConfirmAllProfit", BigDecimal.valueOf(0));

        if(StringHelper.isEmpty(accountId) || StringHelper.isEmpty(phonenum)){
            logger.info("用户accountId={},name={}为空", accountId, phonenum);
            return  fundsObject;
        }
        try {
            int fundsAllCount = 0;
            BigDecimal allFundsMoney = BigDecimal.valueOf(0);
            BigDecimal fundConfirmAllProfit = BigDecimal.valueOf(0);

            try {
                Map<String, Object> ymFundsMap = getymFunds(phonenum, accountId);
                int fundConfirmCounts = (int) ymFundsMap.get("fundConfirmCounts");
                fundsAllCount = fundsAllCount + fundConfirmCounts;
                BigDecimal fundConfirmAllMoney = (BigDecimal) ymFundsMap.get("fundConfirmAllMoney");
                allFundsMoney = allFundsMoney.add(fundConfirmAllMoney);
                fundConfirmAllProfit = (BigDecimal) ymFundsMap.get("fundConfirmAllProfit");
            } catch (Exception e) {
                logger.info("查询已确认基金异常userId={}", userId);
                logger.error("<-----------------------------------error----------------------------------->", e);
            }


            try {
                Map<String, Object> ymWayFundsMap = this.getWayOrder(phonenum, accountId);
                int wayOrderCounts = (int) ymWayFundsMap.get("wayOrderCounts");
                fundsAllCount = fundsAllCount + wayOrderCounts;
                BigDecimal wayMoney = (BigDecimal) ymWayFundsMap.get("wayMoney");
                allFundsMoney = allFundsMoney.add(wayMoney);
            } catch (Exception e) {
                logger.info("查询在途基金异常userId={}", userId);
                logger.error("<-----------------------------------error----------------------------------->", e);
            }
            fundsObject.put("fundsAllCount", fundsAllCount);
            fundsObject.put("allFundsMoney", allFundsMoney);
            fundsObject.put("fundConfirmAllProfit", fundConfirmAllProfit);
        }catch (Exception e){


            logger.error("查询用户基金信息错误 用户accountId={},name={}为空， e={}", accountId, phonenum, e);
        }

        return fundsObject;
    }

    private Map<String, Object> getymFunds(String phone,String accountId) {
        logger.info("getymFunds phone ={}, accountId={}", phone, accountId);
        Map<String, Object> resultMap=new HashMap();
        Map<String, String> params = new HashMap<>();
        params.put("brokerUserId", phone);
        params.put("accountId", accountId);
        params.put("isIncludeZeroShare", "1");
        String fundsList = utils.get("/trade/getFundShares", params);

        logger.info("fundsList = {}", fundsList);

        BigDecimal fundConfirmAllMoney = new BigDecimal(0);
        BigDecimal fundConfirmAllProfit = new BigDecimal(0);
        int fundConfirmCounts=0;
        if (!fundsList.contains("msg")) {
            JSONArray resultArray = new JSONArray(fundsList);
            for (int i = 0; i < resultArray.length(); i++) {
                JSONObject objectStr = resultArray.getJSONObject(i);
                try {
                    BigDecimal totalShare = new BigDecimal(objectStr.get(
                            "totalShare").toString());
                    if(totalShare.compareTo(BigDecimal.valueOf(0))==1){//-1表示小于,0是等于,1是大于
                        fundConfirmCounts++;
                        String nav = objectStr.get("nav").toString();

                        fundConfirmAllMoney = fundConfirmAllMoney.add(new BigDecimal(objectStr.get("totalShareAsset").toString()));
                    }
                    String accumulatedProfit = objectStr.get(
                            "accumulatedProfit").toString();
                    fundConfirmAllProfit = fundConfirmAllProfit
                            .add(new BigDecimal(accumulatedProfit));
                } catch (Exception e) {
                    logger.info("获取盈米确认基金异常!phone={},accountId={}",phone,accountId);
                    logger.error("<-----------------------------------error----------------------------------->", e);
                }
            }

        } else {
            logger.info("获取盈米确认基金失败，phone={}",phone);
        }
        resultMap.put("fundConfirmAllMoney", getBigDecimal(fundConfirmAllMoney));
        resultMap.put("fundConfirmAllProfit", getBigDecimal(fundConfirmAllProfit));
        resultMap.put("fundConfirmCounts", fundConfirmCounts);
        return resultMap;
    }

    private Map<String, Object> getWayOrder(String phone,String accountId)
            throws IOException {
        Map<String, Object> resultMap=new HashMap();
        int wayOrderCounts=0;
        BigDecimal wayMoney=BigDecimal.valueOf(0);
        Map<String, String> paramorder = new HashMap<>();
        paramorder.put("brokerUserId", phone);
        paramorder.put("accountId", accountId);
        String moniZaituOrder = utils.get("/trade/getProcessingFundOrders",
                paramorder);

        logger.info("moniZaituOrder = {}", moniZaituOrder);


        if (!moniZaituOrder.contains("msg")) {
            JSONArray array = new JSONArray(moniZaituOrder);
            wayOrderCounts=array.length();
            BigDecimal wayAllMoney = new BigDecimal(0.0);
            if (wayOrderCounts > 0) {
                for (int i = 0; i < wayOrderCounts; i++) {
                    JSONObject object = array.getJSONObject(i);
                    int payStatus = Integer.valueOf((String) object
                            .get("payStatus"));
                    if (payStatus == 2) {
                        BigDecimal orderMoney = new BigDecimal(object.get(
                                "tradeAmount").toString());
                        wayAllMoney = wayAllMoney.add(orderMoney);
                    }
                }
                wayMoney=wayMoney.add(wayAllMoney);
            }
        } else {
            logger.info("获取在途订单失败phone={},accountId={}",phone,accountId);
        }
        resultMap.put("wayOrderCounts", wayOrderCounts);
        resultMap.put("wayMoney", getBigDecimal(wayMoney));
        return resultMap;
    }


    private BigDecimal getBigDecimal(BigDecimal old) {
        return old == null ? new BigDecimal(0) : old;
    }



}
